#import "Fdset.h"
#import <libc.h>

@implementation Fdset
  
+ new
{
  self = [super new];
  FD_ZERO(&fds);
  FD_ZERO(&ready_fds);
  nfds = 0;
  return self;
}

- addfd:(int)thisfd
{
  FD_SET(thisfd,&fds);
  if (thisfd+1 > nfds)
    nfds = thisfd+1;
  return self;
}

- (BOOL) isfdReady:(int)thisfd // returns YES if given descriptor is ready
{
  return (FD_ISSET(thisfd,&ready_fds));
}

- (int) waitOnInputForever  // returns number of file descriptors which are ready
{
  int nfound;
  ready_fds = fds;
  nfound = select(nfds, &ready_fds, 0,0,0);
  return (nfound);
}

- (int) waitOnInputFor:(int)seconds  //waits no more than number of seconds
{
  int nfound;
  struct timeval timeout;
  timeout.tv_usec = 0;
  timeout.tv_sec = seconds;
  ready_fds = fds;
  nfound = select(nfds, &ready_fds, 0,0, &timeout);
  return (nfound);
}

- (int) waitOnInputFor:(int)seconds :(int)microseconds  // for fractional timeouts
{
  int nfound;
  struct timeval timeout;
  timeout.tv_usec = microseconds;
  timeout.tv_sec = seconds;
  ready_fds = fds;
  nfound = select(nfds, &ready_fds, 0,0, &timeout);
  return (nfound);
}

- (int) getReadyfd  //returns one of the ready file descriptors, marks it unready
{
  int fd;
  for (fd=0; fd<nfds; fd++)
    if (FD_ISSET(fd,&ready_fds)) {
      FD_CLR(fd,&ready_fds);
      return fd;
    }
  return (-1);
}

@end
